package cn.gson.crm.controller.beforesale;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.gson.crm.model.dao.ActionDao;
import cn.gson.crm.model.dao.CustomerDao;
import cn.gson.crm.model.entity.Action;
import cn.gson.crm.model.entity.Customer;
import cn.gson.crm.model.dao.EmployeeDao;
import cn.gson.crm.model.dao.MessageDao;
import cn.gson.crm.model.dao.OpportunityDao;
import cn.gson.crm.model.dao.OrderDao;
import cn.gson.crm.model.entity.Employee;
import cn.gson.crm.model.entity.Message;
import cn.gson.crm.model.entity.Order;
import cn.gson.crm.model.entity.SalesOpportunity;
import cn.gson.crm.model.mapper.CustomerMapper;

@Controller
@RequestMapping("cus")
public class CustomerController {
	@Autowired
	CustomerDao cusDao;

	@Autowired
	CustomerMapper cusMapper;
	
	@Autowired
	EmployeeDao empDao;
	
	@Autowired
	ActionDao acDao;
	
	@Autowired
	OrderDao orDao;
	
	@Autowired
	OpportunityDao oppDao;
	
	@Autowired
	MessageDao messageDao;
	
	@RequestMapping
	public String init() {
		return "beforesale/customer";
	}
	
	//加载新增竞争对手的表单
	@RequestMapping("cusform")
	public String cusForm(){
		return "beforesale/customer/cusform";
	}
	
	//加载编辑客户的表单
	@RequestMapping("cusmoreform/{id}")
	public String cusMoreForm(@PathVariable(required=false) Long id,Model model){
		model.addAttribute("c",cusDao.findOne(id));
		return "beforesale/customer/cusmoreform";
	}
	
	/**
	 * 销售经理和销售人员所看到的客户管理内容是不同的
	 * @param page
	 * @param rows
	 * @return
	 */
	@RequestMapping("list")
	@ResponseBody
	public Map<String, Object> list(@RequestParam(defaultValue = "1")int page,
			@RequestParam(defaultValue = "10") int rows,
			HttpServletRequest req
			){
		Employee emp = (Employee)req.getSession().getAttribute("employee");
		PageRequest pr = new PageRequest(page - 1, rows,new Sort(Direction.DESC,"id"));
		Page<Customer> cus = null;
		if(emp.getRole().getRoleName().equals("销售员")){
			//销售员只能查看自己的客户
			cus = cusDao.findAllByMaStateAndSaStateAndIsDeleteAndEmployee(true,true,false,emp,pr);
		}else{
			//经理显示的客户数据，只需要两个处理都处理好以及没有删除就行。
			cus = cusDao.findAllByMaStateAndSaStateAndIsDelete(true,true,false,pr);
		}
		Map<String, Object> data = new HashMap<>();
		data.put("rows", cus.getContent());
		data.put("total", cus.getTotalElements());
		System.out.println(data);
		return data;
	}
	
	
	@RequestMapping("save")
	@ResponseBody
	@Transactional
	public JSONObject save(@Valid Customer cus,HttpSession session,BindingResult br) {
		JSONObject result = new JSONObject();
		if (br.hasErrors()) {
			//输出错误信息
			Map<String, String> err = new HashMap<String, String>();
			List<FieldError> list = br.getFieldErrors();
			FieldError error = null;
			for (int i = 0; i < list.size(); i++) {
				error = list.get(i);
				err.put(error.getField(), error.getDefaultMessage());
				System.out.println(err);
			}
			result.put("err", "校验失败！");
		}else {
			//通过session读取出当前登录的用户
			Employee emp = (Employee)session.getAttribute("employee");
			cus.setEmployee(emp);
			cusDao.save(cus);
			result.put("success", true);
			messageDao.save(new Message("客户信息", new Date(), null, "新客户信息", emp.getEmpName()+"添加一条新客户信息了！"));
		}

		return result;
	}
	/**
	 * @author PD
	 * 加载客户视图
	 */
	@RequestMapping("view/{id}")
	public String customerview(@PathVariable(required=false) Long id,Model model){
			//查询出当前的用户
		Customer cus = cusDao.findOne(id);
		//System.out.println(cus.toString());
		model.addAttribute("cus",cus);
		return "beforesale/customerview";
	}
	
	/**
	 * @author PD
	 * 加载编辑客户信息表单
	 */
	@RequestMapping("edit/{id}")
	public String editcustomer(@PathVariable(required=false) Long id,Model model){
		Customer cu = cusDao.findOne(id);
		model.addAttribute("cu",cu);
		return "beforesale/customer/editcusviewform";
	}
	
	/**
	 * 三定表单
	 */
	@RequestMapping("sanding/{id}")
	public String sanding(@PathVariable Long id,Model model){
		Customer cus=cusDao.findOne(id);
		model.addAttribute("cus",cus);
		return "beforesale/customer/sandingform";
	}
	
	/**
	 * 三定表单的保存
	 */
	@PostMapping("savecus/{id}")
	public String sanding(@PathVariable Long id,String qualitative,String rank,double ration,Model model){
		
		Customer cuss=cusDao.findOne(id);
		cuss.setQualitative(qualitative);
		cuss.setRank(rank);
		cuss.setRation(ration);
		cusDao.save(cuss);
		//重新查询客户信息
//		Customer cus = cusDao.findOne(id);
//		model.addAttribute("cus",cus);
		return "redirect:../../cus/view/"+id;
	}
	
	
	
	/**
	 * 数据库并没有删除，只是更改了删除状态这个字段，使其不显示
	 * @author PD
	 * 删除客户信息
	 */
	@GetMapping("delete/{id}")
	@ResponseBody
	public Map<String, Object> delete(@PathVariable Long id){
		Map<String, Object> data = new HashMap<>();
		try {
			Customer cus = cusDao.findOne(id);
			cus.setDelete(true);
			cusDao.save(cus);
			data.put("success", true);
		} catch (Exception e) {
			e.printStackTrace();
			data.put("success", false);
			data.put("errorMsg", e.getMessage());
		}
		return data;
	}	
	
	/**
	 * @author PD
	 * 客户转移表单
	 */
	@RequestMapping("change/{id}")
	public String changeowner(@PathVariable Long id,Model model){
		List<Employee> employeelist=empDao.findByState(true);
		Customer cu =cusDao.findOne(id); 
		model.addAttribute("cu",cu);
		model.addAttribute("employeelist",employeelist);
		return "beforesale/customer/changeownerform";
	}
	
	/**
	 * 转移客户功能
	 * @param cuid
	 * @param eeid
	 * @return
	 */
	@GetMapping("savechange")
	@ResponseBody
	public  JSONObject savechangeowner(@RequestParam(value="cuid") Long cuid,@RequestParam(value="eeid") Long eeid){
		JSONObject result = new JSONObject();
		Customer cu = cusDao.findOne(cuid);
		Employee em = empDao.findOne(eeid);
		cu.setEmployee(em);
		cusDao.save(cu);
		if(cusDao.save(cu) != null){
			result.put("message", "客户转移成功！");
		}else{
			result.put("message", "客户转移失败！");
		}
		return result;
	}
	/**
	 * 客户视图界面编辑的保存功能
	 * @param cuid
	 * @param eeid
	 * @return
	 */
	@GetMapping("saveview")
	@ResponseBody
	public  JSONObject saveview(@RequestParam(value="id") Long id,
			@RequestParam(value="name1") String name1,
			@RequestParam(value="ration") double ration,@RequestParam(value="sex") String sex,
			@RequestParam(value="lifecycle") String lifecycle,@RequestParam(value="tel") String tel,
			@RequestParam(value="qualitative") String qualitative,@RequestParam(value="rank") String rank,
			@RequestParam(value="portrayal") String portrayal,@RequestParam(value="email") String email,
			@RequestParam(value="source") String source){
		JSONObject result = new JSONObject();
//		String [] valnum;
//		valnum=val.split("-");
//		String qualitative=valnum[0];
//		String rank = valnum[1];
		//先查询出客户
		Customer cus = cusDao.findOne(id);
		cus.setEmail(email);
		cus.setLifecycle(lifecycle);
		cus.setName(name1);
		cus.setPortrayal(portrayal);
		cus.setQualitative(qualitative);
		cus.setRank(rank);
		cus.setRation(ration);
		cus.setSex(sex);
		cus.setSource(source);
		cus.setTel(tel);
		if(cusDao.save(cus) != null){
			result.put("message", "保存成功！");
		}else{
			result.put("message", "保存失败！");
		}
		return result;
	}
	
	
	
	/**
	 * @author PD
	 * 任务行动表单
	 */
	
	@RequestMapping("action/{id}")
	public String li4(@PathVariable(required=false) Long id,Model model){
		//根据客户id查询客户行动
		Customer cu = cusDao.findOne(id);
		
		List<Action> actions = acDao.findByCustomer(cu);
		model.addAttribute("actions",actions);
		return "beforesale/customer/action";
	}

	
	
	
	/**
	 * @author PD
	 * 合同表单
	 */
	@RequestMapping("pact/{id}")
	public String li2(@PathVariable(required=false) Long id,Model model){
		Customer cu = cusDao.findOne(id);
		//根据客户查到客户对应的所有订单
		List<Order> orders = orDao.findByCustomerAndIsDelete(cu,false);
//		System.out.println(orders.size());
//		for (Order order: orders) {
//			System.out.println(order);
//		}
		model.addAttribute("orders",orders);
		return "beforesale/customer/pactcus";
	}
	
	
	
	
	/**
	 * @author PD
	 * 销售机会表单
	 */
	@RequestMapping("xiaoshou/{id}")
	public String li3(@PathVariable(required=false) Long id,Model model){
		Customer cu = cusDao.findOne(id);
		List<SalesOpportunity> opps = oppDao.findAllByCustomer(cu);
		model.addAttribute("opps",opps);
		return "beforesale/customer/xiaoshou";
	}
	
	/**
	 * @author PD
	 * 官网获得客户，来源互联网
	 */
	@PostMapping("getcus")
	@ResponseBody
	@Transactional
	public JSONObject getCus(@Valid Customer customer,BindingResult br){
		JSONObject result = new JSONObject();
		if (br.hasErrors()) {
			result.put("err", "信息填写错误，请重新填写");
		}else{
		cusDao.save(customer);
		result.put("success", true);
		}	
		return result;
	}
	
	/**
	 * 根据登录身份不同，查询对应的客户。
	 * @author hzl
	 * @return
	 */
	@GetMapping("customerlist")
	@ResponseBody
	public JSONArray getCustomer(HttpServletRequest req){
		Employee employee=(Employee) req.getAttribute("employee");
		JSONArray jsonArray = new JSONArray(); 
		List<Customer> customerlist=new ArrayList<>();
		if("销售员".equals(req.getSession().getAttribute("roleName"))){
			customerlist=cusDao.findAllByEmployee(employee);
		}else{
			customerlist=(List<Customer>) cusDao.findAll();
		}
		if(customerlist.size()>0){
			for (Customer customer : customerlist) {
		        jsonArray.add(customer);  
			}
		}else{
			JSONObject jsonObj=new JSONObject();
			jsonObj.put("id", null);
			jsonObj.put("name", "没有相应的记录");
			jsonArray.add(jsonObj);
		}
		return jsonArray;
	}
	
	/**
	 * 根据id和姓名查询客户信息
	 * @param seacont
	 * @return
	 */
	@PostMapping("search/{seacont}")
	@ResponseBody
	public List<Customer> search(@PathVariable String seacont,Model model){
		List<Customer> cus = new ArrayList<>();
		cus = cusMapper.searchCusname(seacont);
		System.out.println(111);
		return cus;
	}

	/**
	 * 根据id和姓名查询客户信息
	 * @param seaconts
	 * @return
	 */
	@GetMapping("search2/{value}")
	@ResponseBody
	public List<Customer> search2(@PathVariable String value,@RequestParam Long id,Model model){
		List<Customer> cus = new ArrayList<>();
		cus = cusMapper.searchEmpCusname(value, id);
		return cus;
	}
	
	/**
	 * 根据登录用户查询所有客户
	 */
	@RequestMapping("allcustomerlist")
	@ResponseBody
	public JSONArray getCustomer2(HttpSession session ){
		JSONArray jsonArray = new JSONArray();
		Employee emp = (Employee) session.getAttribute("employee");
		if(emp.getEmpName()=="销售主管"){
			List<Customer> customerlist=(List<Customer>) cusDao.findAll();
			if(customerlist.size()>0){
				for (Customer customer : customerlist) {
			        jsonArray.add(customer);  
				}
			}else{
				JSONObject jsonObj=new JSONObject();
				jsonObj.put("id", null);
				jsonObj.put("name", "没有相应的记录");
				jsonArray.add(jsonObj);
			}
		}
		else{
			List<Customer> customerlist=cusMapper.saSelectCus2(emp.getId());
			if(customerlist.size()>0){
				for (Customer customer : customerlist) {
			        jsonArray.add(customer);  
				}
			}else{
				JSONObject jsonObj=new JSONObject();
				jsonObj.put("id", null);
				jsonObj.put("name", "没有相应的记录");
				jsonArray.add(jsonObj);
			}
		}
		return jsonArray;
	}
	
	/**
	 * 查询所有客户
	 */
	@PostMapping("getCustomerList")
	@ResponseBody
	public JSONArray getCustomerList(){
		JSONArray jsonArray = new JSONArray();
		List<Customer> customerlist=(List<Customer>) cusDao.findAll();
		if(customerlist.size()>0){
			for (Customer customer : customerlist) {
		        jsonArray.add(customer);  
			}
		}else{
			JSONObject jsonObj=new JSONObject();
			jsonArray.add(jsonObj);
		}
		return jsonArray;
	}
	
}


